package service

import (
	"context"

	"zhonghui/console/models"
)

func CreateContact(store models.Store, name, corpId string, category, scene int32, channel string, users []string) error {
	return store.ExecTx(context.Background(), func(q *models.Queries) error {
		contactId, err := q.CreateContact(
			context.Background(),
			models.CreateContactParams{
				Name:        name,
				Corpid:      corpId,
				Category:    category,
				Scene:       scene,
				Channel:     channel,
				IsTemp:      false,
				Status:      "config",
				IsExclusive: true,
			},
		)
		if err != nil {
			return err
		}
		for _, user := range users {
			employeeId, err := q.CreateEmployee(context.Background(), models.CreateEmployeeParams{
				Name:        "",
				Phone:       "",
				Avatar:      "",
				AvatarThumb: "",
				Corpid:      corpId,
				UserID:      "",
				OpenUserID:  user,
			})
			if err != nil {
				return err
			}
			err = q.CreateContactEmployee(context.Background(), models.CreateContactEmployeeParams{
				ContactID:  contactId,
				EmployeeID: employeeId,
				Status:     "valid",
			})
			if err != nil {
				return err
			}
		}
		return nil
	})
}

func GetPushContactConfig(store models.Store, id int64) (*models.GetContactEmployeeRow, []string, error) {
	contacts, err := store.GetContactEmployee(context.Background(), id)
	if err != nil {
		return nil, nil, err
	}
	var users []string
	for _, contact := range contacts {
		users = append(users, contact.OpenUserID)
	}
	if len(contacts) == 0 {
		return nil, nil, nil
	}
	return &contacts[0], users, nil
}
